package com.mofei.mall04_fileupload.common.util;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.pdfbox.util.PDFMergerUtility;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import javax.imageio.ImageIO;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class PdfUtil {
    /**
     * @Author Ragty
     * @Description 将图片转换为PDF
     * @Date 15:27 2019/3/4
     * @return
     **/
    public static String Img2PDF(String imagePath,BufferedImage img,String descfolder) throws Exception{
        String pdfPath = "";
        try {
            //图片操作
            Image image = null;
            File file = new File(descfolder);
            //如果没有该文件地址，创建
            if (!file.exists()){
                file.mkdirs();
            }
            //初始化pdf文件地址及文件名
            pdfPath = descfolder +"/"+System.currentTimeMillis()+".pdf";
            // 获取图片类型
            String type = imagePath.substring(imagePath.lastIndexOf(".")+1);
            Document doc = new Document(null, 0, 0, 0, 0);
            //设置新的图片图层
            BufferedImage bufferedImage = new BufferedImage(img.getWidth(), img.getHeight(),BufferedImage.TYPE_3BYTE_BGR);
            //将图片绘制到新的图片图层上
            bufferedImage.getGraphics().drawImage(img, 0,0, img.getWidth(), img.getHeight(), null);
            //根据colorSpace对象构建新的ColorConvertOp，不对源bufferedImage进行颜色转换（内置线性灰度色彩空间）
            bufferedImage=new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB),null).filter (bufferedImage,null);

            /**图片流处理**/
            //以容器左上角为原点，向右下定义一个当前图片大小的矩形区域
            doc.setPageSize(new Rectangle(bufferedImage.getWidth(), bufferedImage.getHeight()));
            //打印图层宽高
            System.out.println(bufferedImage.getWidth()+"()()()()()"+bufferedImage.getHeight());
            //声明一个ByteArrayOutputStream字节数组输出流
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            boolean flag = ImageIO.write(bufferedImage, type, out);
            //实例化一个“字节”类型的新缓冲区
            byte[] b = out.toByteArray();
            //实例化缓冲区
            image = Image.getInstance(b);

            /**写入PDF**/
            //打印pdfPath
            System.out.println("写入PDf:" + pdfPath);
            //初始化文件输出流
            FileOutputStream fos = new FileOutputStream(pdfPath);
            //实例化doc和fos
            PdfWriter.getInstance(doc, fos);
            doc.open();
            //doc文件内插入image图片流
            doc.add(image);
            doc.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (BadElementException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return pdfPath;
    }


    /**
     * @Author Ragty
     * @Description 获取文件夹下的PDF
     * @Date 17:33 2019/3/7
     * @return
     **/
    private static String[] getFiles(String folder) throws IOException {
        File _folder = new File(folder);
        String[] filesInFolder;
        //判断是否为文件夹
        if (_folder.isDirectory()) {
            filesInFolder = _folder.list();
            return filesInFolder;
        } else {
            throw new IOException("Path is not a directory");
        }
    }

    public static void deletePDF(String[] files,String Type) throws Exception{
        for(int i=0;i< files.length;i++){
            StringBuffer sb = new StringBuffer();
            sb.append(files[i]);
            String file = sb.toString();
            if (!file.contains(Type)){
                File deleteFile = new File(file);
                if(!deleteFile.exists()){
                    break;
                }
                if(deleteFile.isFile()&& deleteFile.exists()){
                    deleteFile.delete();
                }
            }
        }
    }

    /**
     * @Author Ragty
     * @Description 合成PDF
     * @Date 17:25 2019/3/7
     * @return
     **/
    public static void mergePDF(String[] files,String desfolder,String mergeFileName) throws Exception{

        PDFMergerUtility mergePdf = new PDFMergerUtility();
        //循环判断 若文件为pdf格式，向声明的mergePdf内添加
        for(int i=0;i< files.length;i++){
            StringBuffer sb = new StringBuffer();
            sb.append(files[i]);
            String file = sb.toString();
            if (file.toLowerCase().endsWith("pdf"))
                mergePdf.addSource(file);
        }

        mergePdf.setDestinationFileName(desfolder+"/"+mergeFileName);
        mergePdf.mergeDocuments();
        System.out.println("merge over");

    }




    public static void main(String[] args,String Type) throws Exception{

        ImgUtil imageUtil = new ImgUtil();
        String[] files = new String[11];
        files[0] = "D:/工作/图片转pdf/测试用文件/1.jpg";
        files[1] = "D:/工作/图片转pdf/测试用文件/2.jpg";
        files[2] = "D:/工作/图片转pdf/测试用文件/3.jpg";
        files[3] = "D:/工作/图片转pdf/测试用文件/4.jpg";
        String folder = "D:/工作/图片转pdf/测试用文件";
        String mergeFileName = "final.pdf";

        for (int i=0;i<files.length;i++) {
            StringBuffer sb = new StringBuffer();
            sb.append(files[i]);
            String file = sb.toString();

            if (file.toLowerCase().endsWith(".png")
                    || file.toLowerCase().endsWith(".jpg")
                    || file.toLowerCase().endsWith(".gif")
                    || file.toLowerCase().endsWith(".jpeg")
                    || file.toLowerCase().endsWith(".gif")) {

                BufferedImage bi = imageUtil.rotateImage(file);
                if (bi==null)
                    continue;

                String pdffile = Img2PDF(file,bi,folder);
                files[i] = pdffile;
            }
        }
        mergePDF(files,folder,mergeFileName);deletePDF(files,Type);

    }

}
